package org.kgc.alanhealth.service.impl;

import org.kgc.alanhealth.entity.HospitalShoppingcart;
import org.kgc.alanhealth.mapper.HospitalShoppingcartMapper;
import org.kgc.alanhealth.service.ShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCarServiceImpl implements ShoppingCarService {
    @Autowired
    HospitalShoppingcartMapper shoppingcartMapper;

    @Override
    public boolean updateStatusById(List<HospitalShoppingcart> shoppingcarts) {
        for (HospitalShoppingcart shoppingcart:shoppingcarts){
            int update=shoppingcartMapper.updateByPrimaryKeySelective(shoppingcart);
               if(update<=0){
                   return false;
            }
        }
        return true;
    }

    @Override
    public boolean insertSelective(HospitalShoppingcart record) {
        // 检查是否已存在相同userId和drugId的记录
        List<HospitalShoppingcart> existingRecords = selectByUserIdAndDrugId(record.getUserid(), record.getDrugname());

        if (!existingRecords.isEmpty()) {
            // 如果存在，更新第一条找到的记录的数量
            HospitalShoppingcart existingRecord = existingRecords.get(0);
            int newQuantity = existingRecord.getDrugnumber() + record.getDrugnumber();
            existingRecord.setDrugnumber(newQuantity);
            return shoppingcartMapper.updateByPrimaryKey(existingRecord) > 0;
        } else {
            // 如果不存在，插入新记录
            record.setStatus(1);
            return shoppingcartMapper.insert(record) > 0;
        }
    }

    @Override
    public List<HospitalShoppingcart> selectByUserid(int id) {
        return shoppingcartMapper.selectByUserid(id);
    }

    @Override
    public boolean deleteByPrimaryKey(Long id) {
        return shoppingcartMapper.deleteByPrimaryKey(id)>0;
    }

    @Override
    public List<HospitalShoppingcart> selectByUserIdAndDrugId(int userid, String drugname) {
        return shoppingcartMapper.selectByUserIdAndDrugId(userid, drugname);
    }
}
